import { defineStore } from "pinia"
import { onMounted, reactive, ref } from "vue"
import { MessagePlugin } from "tdesign-vue-next"
import { get, post } from "@/utils/api"

export const useAdminProgramStore = defineStore("adminProgram", () => {

  onMounted(async () => {
    await table.getData()
  })
  // 表格模块
  const table = {
    data: reactive([]),
    loading: ref(false),
    getData: async () => {
      table.loading.value = true
      try {
        table.data = await get("/api/program/getAll")
      } catch (err) {
        console.log(err)
      } finally {
        table.loading.value = false
      }
    },
    key: ref(0),
    searchData: ref(""),
    search: async () => {
      table.loading.value = true
      table.data = await post("/api/program/search", { name: table.searchData.value })
      table.loading.value = false
    },
    refresh: async () => {
      await table.getData()
      table.key.value++
      table.searchData.value = ""
    }
  }
  // 添加模块
  const addDialog = {
    visible: ref(false),
    loading: ref(false),
    add: async ({ validateResult, firstError, e }: any) => {
      e.preventDefault()
      if (validateResult === true) {
        await addDialog.confirmAdd()
      } else {
        console.log("Validate Errors: ", firstError, validateResult)
      }
    },
    confirmAdd: async () => {
      addDialog.loading.value = true
      try {
        const response = await post("/api/program/add", common.formData)
        MessagePlugin(response.status, response.message)
        if(response.status === "success"){
          addDialog.visible.value = false
          await table.getData()
          table.key.value++ // 重新渲染表格
        }
      } catch (err) {
        await MessagePlugin("error", "系统错误，请稍后再试~")
        console.log(err)
      } finally {
        addDialog.loading.value = false
      }
    }

  }
  // 编辑模块
  const editDialog = {
    visible: ref(false),
    loading: ref(false),
    editId: ref(),
    editName: ref(), // 解决修改应用信息应用名重复问题
    formDataAssign: (row: any) => {
      editDialog.visible.value = true
      const { id, name, download, img } = row
      editDialog.editId.value = id
      editDialog.editName.value = name // 用来判断应用名是否重复
      upload.download.data.value = [{
        name: download.slice(download.lastIndexOf("/") + 1),
        url: download,
        status: "success",
      }] as any
      upload.img.data.value = [{
        name: img.slice(img.lastIndexOf("/") + 1),
        url: img,
        status: "success"
      }] as any
      row.cycle = row.cycle.toString()
      Object.assign(common.formData, row)
    },
    edit: async ({ validateResult, firstError, e }: any) => {
      e.preventDefault()
      if (validateResult === true) {
        await editDialog.confirmEdit()
      } else {
        console.log("Validate Errors: ", firstError, validateResult)
      }
    },
    confirmEdit: async () => {
      editDialog.loading.value = true
      try {
        const response = await post("/api/program/update", {
            id: editDialog.editId.value,
            data: common.formData,
            name: editDialog.editName.value
          })
        MessagePlugin(response.status, response.message)
        if(response.status === "success"){
          editDialog.visible.value = false
          await table.getData()
          table.key.value++ // 重新渲染表格
        }
      } catch (err) {
        console.log(err)
      } finally {
        editDialog.loading.value = false
      }
    },
    updateStatus: async (row: any) => {
      const { id, status } = row
      try {
        const response = await post("/api/program/updateStatus", { id, status })
        MessagePlugin(response.status, response.message)
      } catch (err) {
        await MessagePlugin("error", "系统错误，请稍后再试~")
        console.log(err)
      }
    }
  }
  // 公共模块
  const common = {
    formData: reactive({
      name: "",
      price: "",
      download: "",
      img: "",
      status: 1,
      cycle: "24",
      description: ""
    }),
    clear: () => {
      Object.assign(common.formData, {
        name: "",
        price: "",
        download: "",
        img: "",
        status: 1,
        cycle: "24",
        description: ""
      })
      upload.img.data.value = []
      upload.download.data.value = []
    },
    validator: {
      priceValidator: (val: string | number) => {
        const regex = /^[+-]?\d+(\.\d+)?$/
        if (!regex.test(val.toString().replace(/"/g, ""))) {
          return { result: false, message: "请输入数字", type: "error" }
        }
        if (Number(val) === 0){
          return { result: false, message: "价格不能为0", type: "error" }
        }
        return { result: true }
      },
      cycleValidator: (val: string | number) => {
        const regex = /^[0-9]+$/
        if (!regex.test(val.toString().replace(/^"|"$/g, ""))) {
          return { result: false, message: "请输入整数", type: "error" }
        }
        return { result: true }
      },
    },
    rules: {
      name: [{ required: true, trigger: "change" }],
      price: [{ required: true, trigger: "change" }, { validator: (val: any) => common.validator.priceValidator(val) }],
      download: [{ required: true, trigger: "change" }],
      img: [{ required: true, trigger: "change" }],
      status: [{ required: true, trigger: "change" }],
      cycle: [{
        required: true,
        trigger: "change"
      }, { validator: (val: string | number) => common.validator.cycleValidator(val) }],
      description: [{ required: true, trigger: "change" }]
    }
  }
  // 删除模块
  const deleteDialog = {
    deleteId: ref(),
    deleteIds: ref([]),
    deleteIdsChange: (value: any) => {
      deleteDialog.deleteIds.value = value
    },
    visible: ref(),
    groupVisible: ref(),
    loading: ref(false),
    groupLoading: ref(false),
    delete: (id: number | string) => {
      deleteDialog.visible.value = true
      deleteDialog.deleteId.value = id
    },
    confirmDelete: async () => {
      deleteDialog.loading.value = true
      try {
        const response = await post("/api/program/delete", { id: deleteDialog.deleteId.value })
        MessagePlugin(response.status, response.message)
        await table.getData()
        table.key.value++ // 重新渲染表格
      } catch (err) {
        console.log(err)
        await MessagePlugin("error", "系统错误，请稍后再试~")
      } finally {
        deleteDialog.loading.value = false
        deleteDialog.visible.value = false
      }
    },
    isGroupEmpty: async () => {
      if( deleteDialog.deleteIds.value.length === 0){
        await MessagePlugin("error", "删除失败，数据为空！")
      }else{
        deleteDialog.groupVisible.value = true
      }
    },
    confirmDeleteGroup: async () => {
      try {
        const response = await post("/api/program/deleteGroup", { ids: deleteDialog.deleteIds.value })
        MessagePlugin(response.status, response.message)
        await table.getData()
        table.key.value++ // 重新渲染表格
      } catch (err) {
        console.log(err)
        await MessagePlugin("error", "系统错误，请稍后再试~")
      } finally {
        deleteDialog.groupLoading.value = false
        deleteDialog.groupVisible.value = false
      }
    }
  }
  // 文件上传模块
  const upload = {
    img: {
      data: ref([]),
      success: (params: any) =>{
        common.formData.img = params.response.url
        console.log(upload.img.data)
      },
      remove: () =>{
        common.formData.img = ""
        console.log(upload.img.data)
      }
    },
    download: {
      data: ref([]),
      success: (params: any) =>{
        common.formData.download = params.response.url
      },
      remove: () =>{
        common.formData.download = ""
      }
    },
    fail: async () =>{
      await MessagePlugin.error("文件上传失败！")
    }
  }

  return {
    table,
    common,
    addDialog,
    editDialog,
    deleteDialog,
    upload
  }
})
